<template>
  <div class="app-container">

    <div class="filter-container">
      <el-select v-model="housingQuery.building" placeholder="请选择区域" clearable style="width: 150px" class="filter-item" @keyup.enter.native="handleFilter" @change="queryBuildingChange()">
        <el-option v-for="item in buildingOptions" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
      <el-select v-model="housingQuery.floor" placeholder="请选择楼层" clearable style="width: 150px" class="filter-item" @keyup.enter.native="handleFilter">
        <el-option v-for="item in floorOptions" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
      <el-input v-model="housingQuery.rno" placeholder="宿舍号" clearable style="width: 150px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="housingQuery.sno" placeholder="学号" clearable style="width: 150px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="housingQuery.name" placeholder="姓名" clearable style="width: 150px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-date-picker v-model="housingQuery.begin" type="datetime" style="width: 200px;" placeholder="开始时间" class="filter-item" value-format="yyyy-MM-dd HH:mm:ss" @keyup.enter.native="handleFilter" />
      <el-date-picker v-model="housingQuery.end" type="datetime" style="width: 200px;" placeholder="结束时间" class="filter-item" value-format="yyyy-MM-dd HH:mm:ss" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        导出
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column label="区域" width="100" align="center">
        <template slot-scope="scope">
          {{ scope.row.buildingDesc }}
        </template>
      </el-table-column>
      <el-table-column label="楼层" width="100" align="center">
        <template slot-scope="scope">
          {{ scope.row.floorDesc }}
        </template>
      </el-table-column>
      <el-table-column label="宿舍号" width="100" align="center">
        <template slot-scope="scope">
          {{ scope.row.rno }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="姓名" width="150">
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="right">
            <p>学号: {{ scope.row.sno }}</p>
            <p>姓名: {{ scope.row.name }}</p>
            <div slot="reference" class="name-wrapper">
              <el-tag size="medium">{{ scope.row.name }}</el-tag>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column align="center" label="类型" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.type | typeFilter">
            {{ scope.row.type }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="爱好" width="240" align="center">
        <template slot-scope="scope">
          <div v-if="scope.row.hobby.length > 0">
            <el-tag v-for="item in scope.row.hobby.split(',')" :key="item" type="success">{{ item }}</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="习惯" width="200" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.habit }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划" width="200" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.plan }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="时间" width="200">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>{{ scope.row.gmtCreate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="medium" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="medium" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="page" :limit.sync="limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form ref="dataForm" :rules="rules" :model="housingVo" label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item label="区域" prop="building">
          <el-select v-model="housingVo.building" placeholder="请选择区域" clearable style="width: 300px;" @change="buildingChange()">
            <el-option v-for="item in buildingOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="楼层" prop="floor">
          <el-select v-model="housingVo.floor" placeholder="请选择楼层" clearable style="width: 300px;">
            <el-option v-for="item in floorOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="宿舍号" prop="rno">
          <el-input v-model="housingVo.rno" />
        </el-form-item>
        <el-form-item label="学号" prop="sno">
          <el-input v-model="housingVo.sno" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="housingVo.type" placeholder="请选择类型" clearable style="width: 300px;">
            <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="爱好" prop="hobby">
          <el-select
            v-model="hobbise"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请输入爱好"
            :change="hobbiseChange()"
            style="width: 300px"
          />
        </el-form-item>
        <el-form-item label="习惯" prop="habit">
          <el-input v-model="housingVo.habit" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="请输入习惯" />
        </el-form-item>
        <el-form-item label="计划" prop="plan">
          <el-input v-model="housingVo.plan" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="请输入计划" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getList, remove, save, update, getHousing, buildingList, floorListById } from '@/api/housing'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  components: { Pagination },
  directives: { waves },
  filters: {
    typeFilter(type) {
      const typeMap = {
        '入住': 'success',
        '离宿': 'danger'
      }
      return typeMap[type]
    }
  },
  data() {
    return {
      list: null,
      listLoading: true,
      total: 0,
      page: 1,
      limit: 10,
      housingQuery: {
        building: '',
        floor: '',
        rno: '',
        sno: '',
        name: '',
        type: '',
        begin: '',
        end: ''
      },
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加'
      },
      housingVo: {
        id: '',
        building: '',
        buildingDesc: '',
        floor: '',
        floorDesc: '',
        roomId: '',
        rno: '',
        studentId: '',
        sno: '',
        name: '',
        type: '',
        hobby: '',
        habit: '',
        plan: ''
      },
      hobbise: [],
      dialogFormVisible: false,
      rules: {
        building: [{ required: true, message: '区域不能为空', trigger: 'blur' }],
        floor: [{ required: true, message: '楼层不能为空', trigger: 'blur' }],
        rno: [{ required: true, message: '宿舍号不能为空', trigger: 'blur' }],
        sno: [{ required: true, message: '检查学生不能为空', trigger: 'blur' }],
        type: [{ required: true, message: '类型不能为空', trigger: 'blur' }]
      },
      downloadLoading: false,
      typeOptions: [{ label: '入住', value: '1' }, { label: '离宿', value: '0' }],
      buildingOptions: [],
      floorDisabled: true,
      floorOptions: []
    }
  },
  created() {
    this.getList()
    buildingList().then((response) => {
      this.buildingOptions = response.data
    })
  },
  methods: {
    getList() {
      this.listLoading = true
      getList(this.page, this.limit, this.housingQuery).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.page = 1
      this.getList()
    },
    queryBuildingChange() {
      this.floorOptions = []
      this.housingQuery.floor = ''
      if (this.housingQuery.building !== '') {
        floorListById(this.housingQuery.building).then(response => {
          this.floorOptions = response.data
          this.floorDisabled = false
        })
      }
    },
    buildingChange() {
      this.floorOptions = []
      this.housingVo.floor = ''
      this.housingVo.floorDesc = ''
      if (this.housingVo.building !== '') {
        floorListById(this.housingVo.building).then(response => {
          this.floorOptions = response.data
          this.floorDisabled = false
        })
      }
    },
    hobbiseChange() {
      if (this.hobbise.length > 0) {
        this.housingVo.hobby = this.hobbise.join(',')
      } else {
        this.housingVo.hobby = ''
      }
    },
    handleCreate() {
      this.resethousingVo()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    resethousingVo() {
      this.housingVo = {
        id: '',
        building: '',
        buildingDesc: '',
        floor: '',
        floorDesc: '',
        roomId: '',
        rno: '',
        studentId: '',
        sno: '',
        name: '',
        type: '',
        hobby: '',
        habit: '',
        plan: ''
      }
      this.floorDisabled = true
      this.floorOptions = []
      this.hobbise = []
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          save(this.housingVo).then((response) => {
            this.dialogFormVisible = false
            this.list.unshift(response.data)
            this.$notify({
              title: 'Success',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    async handleUpdate(row) {
      // 获取宿舍信息
      const res = await getHousing(row.id)
      this.housingVo = res.data
      this.hobbise = res.data.hobby.split(',')
      // 根据宿舍信息获取楼栋和楼层
      const floorList = await floorListById(this.housingVo.building)
      this.floorDisabled = false
      this.floorOptions = floorList.data
      this.housingVo.type = this.housingVo.type === '入住' ? '1' : '0'
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          update(this.housingVo).then((response) => {
            this.dialogFormVisible = false
            const index = this.list.findIndex(v => v.id === response.data.id)
            this.list.splice(index, 1, response.data)
            this.$notify({
              title: 'Success',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$notify({
        title: 'Success',
        message: '删除成功',
        type: 'success',
        duration: 2000
      })
      this.list.splice(index, 1)
      remove(row.id)
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['区域', '楼层', '宿舍号', '学号', '姓名', '类型', '申请时间']
        const filterVal = ['buildingDesc', 'floorDesc', 'rno', 'sno', 'name', 'type', 'gmtCreate']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '入住离宿信息'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>
<style scoped>
.el-tag {
  margin: 5px;
}
</style>
